package Models

import (
	"fmt"
	global "gPublic/Global"
	"gPublic/Viper"

	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB
var err error

func init() {
	Viper.ViperTest()
	DB_Host := global.Config.MysqlYZInfo.DB_Host
	DB_PASSWORD := global.Config.MysqlYZInfo.DB_PASSWORD
	DB_USERNAME := global.Config.MysqlYZInfo.DB_USERNAME
	DB_PORT := global.Config.MysqlYZInfo.DB_PORT
	DB_DATABASE := global.Config.MysqlYZInfo.DB_DATABASE
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", DB_USERNAME, DB_PASSWORD, DB_Host, DB_PORT, DB_DATABASE)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second,
			LogLevel:                  logger.Info,
			IgnoreRecordNotFoundError: true,
			Colorful:                  true,
		},
	)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                 newLogger,
		SkipDefaultTransaction: false,
	})

	sqlDB, err := DB.DB()
	if err != nil {
		fmt.Println("链接失败：", err)
	} else {
		// 设置默认连接数
		sqlDB.SetMaxIdleConns(10)
		sqlDB.SetMaxOpenConns(100)
	}
}
